Chapter 6: URLs and Class-based Views
For the API app to have its own urls.py to contain the paths for the API end points, we add the below to
todobackend/backend/urls.py:
Modify Bold Code
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
]
This will forward all API related paths e.g. localhost:8000/api/* to the API app.
Creating our first route
In /todobackend/api/, create a new file urls.py which will contain the routes of the different endpoints. Add in the
below code:
Add Code
from django.urls import path
from . import views
urlpatterns = [
path('todos/', views.TodoList.as_view()),
]
We have one route ‘/todos’ as a demonstration. What we want to achieve is that when a request is made to
localhost:8000/api/todos, you should get a JSON response with the list of todo instances. But how do we achieve
this?
The answer is in views.TodoList.as_view().
In traditional full stack Django projects, views are used to customize what data to send to the HTML templates. In
our API project, we use class-based generic views (from DRF) to similarly send customized serialized data but this
time, to the API endpoints instead of to templates.
views.TodoList is an instance of a class-based generic view. Django’s generic views help us quickly write views
(without having to write too much repetitive code) to do common tasks like:
- Display a list of objects, e.g. list of todos.
- Display detail pages for a single object. E.g. detail page of a todo.
- Allow users to create, update, and delete objects – with or without authorization.
Things will be clearer as we implement our TodoList generic view. Thus, in todobackend/api/views.py, replace the
code with the following:
Replace Entire Code
from rest_framework import generics
from .serializers import TodoSerializer
from todo.models import Todo
class TodoList(generics.ListAPIView):
# ListAPIView requires two mandatory attributes, serializer_class and
# queryset.
# We specify TodoSerializer which we have earlier implemented
serializer_class = TodoSerializer
def get_queryset(self):
user = self.request.user
return Todo.objects.filter(user=user).order_by('-created')
Code Explanation
Analyze Code
from rest_framework import generics
We import DRF ’ s generics class of views.
Analyze Code
class TodoList(generics.ListAPIView):